<!-- 问卷管理 -->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button round size="medium" type="primary" @click="handleCreate">新增</el-button>
      <el-input v-model="query.keyword" placeholder="请输入问卷名进行搜索" style="width: 200px;margin-left: 10px;"
                class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-button size="medium" style="margin-left: 10px;" v-waves class="filter-item" type="primary"
                 icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
    </div>

    <el-table
      style="margin-top: 20px;width: 100%;"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      :fit="true"
      highlight-current-row
    >
      <el-table-column type="expand" v-if="resList.length>0">
        <template slot-scope="{row}" v-if="row.id===whichOne">
          <el-form label-position="left" inline class="demo-table-expand" v-for="item in resList" :key="item.id">
            <el-form-item label="轮次">
              <span>第{{ item.result_round }}轮</span>
            </el-form-item>
            <el-form-item label="已回答人数" style="margin-left: 30px;">
              <span>{{ item.count }}人</span>
            </el-form-item>
            <el-form-item label="最大值平均值" style="margin-left: 30px;">
              <span>{{ item.max_average.toFixed(2) }}¥</span>
            </el-form-item>
            <el-form-item label="最可能值平均值" style="margin-left: 30px;">
              <span>{{ item.possible_average.toFixed(2) }}¥</span>
            </el-form-item>
            <el-form-item label="最小值平均值" style="margin-left: 30px;">
              <span>{{ item.min_average.toFixed(2) }}¥</span>
            </el-form-item>
            <el-form-item label="加权平均值" style="margin-left: 30px;">
              <span>{{ item.estimate.toFixed(2) }}¥</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="100">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="问卷名称" align="center" width="200">
        <template slot-scope="{row}">
          {{ row.title }}
        </template>
      </el-table-column>
      <el-table-column label="问卷轮次" align="center" width="100">
        <template slot-scope="{row}">
          <span v-if="row.round<0">评测结束</span>
          <span v-else>{{ row.round ? `第${row.round}轮` : '未开始' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.question_time | dayFormatTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createAt | dayFormatTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center">
        <template slot-scope="{row}">
          {{ row.updateAt | dayFormatTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="{row,$index}">
          <el-button-group>
            <el-button type="warning" round size="small" @click="handleExpert(row)">专家</el-button>
            <el-button v-if="row.round>=0" type="success" size="small" @click="handleUpdate(row)">发布</el-button>
            <el-button type="info" size="small" @click="handleProcess(row)">{{ row.round === -1 ? '结果' : '进展' }}
            </el-button>
            <el-button v-if="row.round>0" type="primary" size="small" @click="handleFinish(row)">结束</el-button>
            <el-button type="danger" round size="small" @click="handleDelete(row,$index)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      style="text-align: right"
      v-show="total>0"
      :total="total"
      :page.sync="query.offset"
      :limit.sync="query.limit"
      @pagination="getList"
    />

    <!-- 新增和编辑对话框 -->
    <el-dialog :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="80px" label-position="left">
        <el-form-item label="问卷名称" prop="title">
          <el-input v-model="temp.title" placeholder="请输入问卷名称"/>
        </el-form-item>
        <el-form-item label="问卷头" prop="header">
          <el-input type="textarea" v-model="temp.header" :rows="3" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="截止时间" prop="question_time">
          <el-date-picker
            v-model="temp.question_time"
            type="datetime"
            :picker-options="pickerOptions"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="对应物品" prop="materials_id">
          <el-select filterable v-model="temp.materials_id" :disabled="temp.round>0" clearable placeholder="请选择">
            <el-option
              v-for="item in applyList"
              :key="item.id"
              :label="item.thing_name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择问卷" prop="config_id">
          <el-select filterable v-model="temp.config_id" :disabled="temp.round>0" clearable placeholder="请选择">
            <el-option
              v-for="item in configList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 选择专家 -->
    <el-dialog :visible.sync="dialogExpertVisible" title="参与专家">
      <el-form :model="temp" label-width="80px" label-position="left">
        <el-form-item label="参与专家">
          <el-select v-model="joinExperts" @change="expertChange" disabled multiple clearable
                     placeholder="请选择">
            <el-option
              v-for="item in temp.Users"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, create, fetchDetail, remove, update, recommendExpert, resultList } from '@/api/question'
import { userList } from '@/api/user'
import { fetchList as fetchConfig } from '@/api/config'
import { changeStatus, fetchList as fetchApply } from '@/api/apply'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import waves from '@/directive/waves'
import user from '@/store/modules/user' // waves directive

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      total: 0,
      whichOne: '',
      query: {
        limit: 10,
        offset: 1,
        keyword: ''
      },
      textMap: {
        update: '编辑',
        create: '新增'
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      dialogFormVisible: false,
      dialogExpertVisible: false,
      dialogStatus: '',
      list: null,
      listLoading: true,
      temp: {
        title: '',
        header: '',
        materials_id: '',
        config_id: '',
        question_time: '',
        round: 0
      },
      rules: {
        title: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
        header: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
        materials_id: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
        question_time: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
        config_id: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
      },
      applyList: [], // 申请物品的数组
      configList: [], // 配置问卷的数组
      joinExperts: [], // 参与的专家
      resList: [] // 结果列表
    }
  },
  created() {
    this.getList()
    this.getApplyList()
    this.getConfigList()
  },
  methods: {
    handleFilter() {
      this.query.offset = 1
      this.getList()
    },
    getResultList(question_id) {
      resultList({ question_id }).then(res => {
        this.resList = res.data.list
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.query).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getApplyList() {
      fetchApply({ limit: 1000, offset: 1, keyword: '' }).then(response => {
        this.applyList = response.data.list.filter(it => {
          return it.approval_status === 1
        })
      })
    },
    // 获取配置列表
    getConfigList() {
      fetchConfig({ limit: 1000, offset: 1, keyword: '' }).then(res => {
        this.configList = res.data.list
      })
    },
    // 监听选择专家的变化
    expertChange() {

    },
    // 进展
    handleProcess(row) {
      this.getResultList(row.id)
      this.whichOne = row.id
    },
    // 专家
    handleExpert(row) {
      this.dialogExpertVisible = true
      this.temp = Object.assign({}, row) // copy obj
      // 展示自动选择的专家
      this.joinExperts = this.temp.Users.map(it => {
        return it.id
      })
    },
    // 结束
    handleFinish(row) {
      update({
        id: row.id,
        round: -1
      }).then(res => {
        changeStatus({ id: row.materials_id, status: 3 }).then(res => {
          this.$notify({
            title: '成功',
            message: '已结束',
            type: 'success',
            duration: 1000
          })
          this.getList()
        })
      })
    },
    // 发布
    handlePublish(row) {
      update({
        id: row.id,
        round: row.round + 1
      }).then(() => {
        this.getList()
        return new Promise((resolve, reject) => {
          resolve()
        })
      }).then(data => {
        if (row.round < 1) return
        recommendExpert({
          question_id: row.id,
          materials_id: row.materials_id,
          question_round: row.round + 1
        }).then(response => {
          this.getList()
        })
      })
    },
    resetTemp() {
      this.temp = {
        title: '',
        header: '',
        materials_id: '',
        config_id: '',
        question_time: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      if (this.$refs['dataForm']) {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then((res) => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 1000
            })
            return new Promise((resolve, reject) => {
              resolve(res.data)
            })
          }).then(data => {
            recommendExpert({
              question_id: data.id,
              materials_id: data.materials_id,
              question_round: 1
            }).then(response => {
              this.getList()
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if (this.$refs['dataForm']) {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            this.handlePublish(tempData)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 1000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确定删除吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          remove(row.id).then(res => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1000
            })
            this.getList()
          })
        })
        .catch(err => {
          console.error(err)
        })
    }
  }
}
</script>
